#!/usr/bin/perl

package ExcelReporter;

use strict;
use warnings;
use Excel::Writer::XLSX;
use Spreadsheet::ParseXLSX;
use Utils qw(dd);
use Log;
use Consts;
use POSIX qw(strftime);

my $workbook;

sub new
{
    my ($class, %args) = @_;
    my $self = {
        path     => $Consts::DATA_PATH . "/" . $args{time} || $Consts::DATA_PATH,
        filename => $args{filename},
        sheets   => $args{sheets} ? [@{$args{sheets}}] : [],
    };

    # 从配置文件中读取子目录名称
    my $subdir = $args{subdir};
    $self->{path} .= "/". $subdir;

    unless (-e $self->{path}) {
        Utils::_mkdir($self->{path});
    }
    bless $self, $class;
    return $self;
}

sub addWorksheet
{
    my ($self, $sheetname, $headers) = @_;
    my %worksheet = (
        name     => $sheetname,
        headers  => $headers,
        data     => [],
    );
    push @{$self->{sheets}}, \%worksheet;
    return $self;
}

sub getPath
{
    my $self = shift;
    return $self->{path};
}

sub getWorksheet
{
    my ($self, $sheetname) = @_;
    foreach my $worksheet (@{$self->{sheets}}) {
        if ($worksheet->{name} eq $sheetname) {
            return $worksheet;
        }
    }
}

sub addWorksheetData
{
    my ($self, $sheetname, @data) = @_;
    my $worksheet = $self->getWorksheet($sheetname);
    if ($worksheet) {
        push @{$worksheet->{data}}, @data;
    }
    return $self;
}

sub getRealpath
{
    my $self = shift;
    return $self->{path}. "/". $self->{filename};
}

sub doExport
{
    my $self = shift;
    my $sheetname = shift;
    my $worksheet = $self->getWorksheet($sheetname);
    if (!$worksheet) {
        Log::error("Worksheet $sheetname not found");
        return $self;
    }
    my $excel_filename = getRealpath($self);

    unless (defined $workbook) {
        $workbook = Excel::Writer::XLSX->new($excel_filename);
    }
    my $sheet = $workbook->add_worksheet($worksheet->{name});
    for my $col (0.. $#{$worksheet->{headers}}) {
        $sheet->write(0, $col, $worksheet->{headers}[$col]);
    }
    for my $row (0.. $#{$worksheet->{data}}) {
        for my $col (0.. $#{$worksheet->{data}[$row]}) {
            if (isLink($worksheet->{data}[$row][$col])) {
                $sheet->write_url($row + 1, $col, $worksheet->{data}[$row][$col]);
            } else {
                $sheet->write($row + 1, $col, $worksheet->{data}[$row][$col]);
            }
        }
    }

    return $self;
}

sub close
{
    my $self = shift;
    $workbook->close();
    $workbook = undef;
    $self->{path} = undef;
    $self->{filename} = undef;
    $self->{sheets} = [];
    return $self;
}

sub isLink
{
    my $value = shift;
    unless (defined $value) {
        return 0;
    }
    return $value =~ /\.xlsx$/;
}

1;
